package com.itheima.mm.controller;

import com.itheima.mm.constants.Constants;
import com.itheima.mm.entity.Result;
import com.itheima.mm.pojo.User;
import com.itheima.mm.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 包名:com.itheima.mm.controller
 * 作者:Leevi
 * 日期2020-01-15  10:15
 */
@RestController
@RequestMapping("user")
public class UserController {
    @Autowired
    private IUserService userService;

    @RequestMapping("logout")
    public Result logout(HttpSession session) throws IOException {
        //销毁session对象
        session.invalidate();
        return new Result(true,"退出成功");
    }

    @RequestMapping("login")
    public Result login(@RequestBody User loginUser,HttpSession session) throws IOException {
        //1. 封装请求参数
        try {
            //2. 调用业务层的方法，处理登录
            User user = userService.login(loginUser);
            //登录成功,将user对象存储到session总
            session.setAttribute(Constants.MM_USER_USERNAME,user);
            //System.out.println(user);
            //封装响应数据，响应给客户端
            return new Result(true,"登录成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,e.getMessage());
        }
    }
}
